package com.unionpay.upyzt.spring.example.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

import static java.lang.Math.*;

public class DoubleUtil {
    /**
     * double四舍五入保留小数
     * @param value
     * @param places
     * @return
     */
    public static Double round(Double value, int places) {
        if (value == null) {
            return null;
        }
        BigDecimal bd = BigDecimal.valueOf(value);
        bd = bd.setScale(places, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    public static Double calculateDistance(Double lon1, Double lat1,Double lon2, Double lat2) {
        // 地球半径，单位为米
        double EARTH_RADIUS = 6371000;
        // 实现Haversine公式计算两点之间的距离
        double latDistance = toRadians(lat2 - lat1);
        double lonDistance = toRadians(lon2 - lon1);
        double a = sin(latDistance / 2) * sin(latDistance / 2) +
                cos(toRadians(lat1)) * cos(toRadians(lat2)) *
                        sin(lonDistance / 2) * sin(lonDistance / 2);
        double c = 2 * atan2(sqrt(a), sqrt(1 - a));
        // 返回单位为公里的距离
        BigDecimal distance = new BigDecimal(EARTH_RADIUS * c / 1000);
        Double formattedDistance = distance.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        return formattedDistance;
    }
}
